GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

ocLazyLoad.loaders.common.js ➔ buildElement   F
last analyzed

Complexity

Conditions 28

Size

Total Lines 111
Code Lines 73

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 28
eloc 73
dl 0
loc 111
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like ocLazyLoad.loaders.common.js ➔ buildElement often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
(function (angular) {
2
    'use strict';
3
4
    angular.module('oc.lazyLoad').config(["$provide", function ($provide) {
5
        $provide.decorator('$ocLazyLoad', ["$delegate", "$q", "$window", "$interval", function ($delegate, $q, $window, $interval) {
6
            var uaCssChecked = false,
7
                useCssLoadPatch = false,
8
                anchor = $window.document.getElementsByTagName('head')[0] || $window.document.getElementsByTagName('body')[0];
9
10
            /**
11
             * Load a js/css file
12
             * @param type
13
             * @param path
14
             * @param params
15
             * @returns promise
16
             */
17
            $delegate.buildElement = function buildElement(type, path, params) {
18
                var deferred = $q.defer(),
19
                    el,
20
                    loaded,
21
                    filesCache = $delegate._getFilesCache(),
22
                    cacheBuster = function cacheBuster(url) {
23
                    var dc = new Date().getTime();
24
                    if (url.indexOf('?') >= 0) {
25
                        if (url.substring(0, url.length - 1) === '&') {
26
                            return url + '_dc=' + dc;
27
                        }
28
                        return url + '&_dc=' + dc;
29
                    } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
30
                        return url + '?_dc=' + dc;
31
                    }
32
                };
33
34
                // Store the promise early so the file load can be detected by other parallel lazy loads
35
                // (ie: multiple routes on one page) a 'true' value isn't sufficient
36
                // as it causes false positive load results.
37
                if (angular.isUndefined(filesCache.get(path))) {
38
                    filesCache.put(path, deferred.promise);
39
                }
40
41
                // Switch in case more content types are added later
42
                switch (type) {
43
                    case 'css':
44
                        el = $window.document.createElement('link');
45
                        el.type = 'text/css';
46
                        el.rel = 'stylesheet';
47
                        el.href = params.cache === false ? cacheBuster(path) : path;
48
                        break;
49
                    case 'js':
50
                        el = $window.document.createElement('script');
51
                        el.src = params.cache === false ? cacheBuster(path) : path;
52
                        break;
53
                    default:
54
                        filesCache.remove(path);
55
                        deferred.reject(new Error('Requested type "' + type + '" is not known. Could not inject "' + path + '"'));
56
                        break;
57
                }
58
                el.onload = el['onreadystatechange'] = function (e) {
59
                    if (el['readyState'] && !/^c|loade/.test(el['readyState']) || loaded) return;
60
                    el.onload = el['onreadystatechange'] = null;
61
                    loaded = 1;
62
                    $delegate._broadcast('ocLazyLoad.fileLoaded', path);
63
                    deferred.resolve(el);
64
                };
65
                el.onerror = function () {
66
                    filesCache.remove(path);
67
                    deferred.reject(new Error('Unable to load ' + path));
68
                };
69
                el.async = params.serie ? 0 : 1;
70
71
                var insertBeforeElem = anchor.lastChild;
72
                if (params.insertBefore) {
73
                    var element = angular.element(angular.isDefined(window.jQuery) ? params.insertBefore : document.querySelector(params.insertBefore));
74
                    if (element && element.length > 0) {
75
                        insertBeforeElem = element[0];
76
                    }
77
                }
78
                insertBeforeElem.parentNode.insertBefore(el, insertBeforeElem);
79
80
                /*
81
                 The event load or readystatechange doesn't fire in:
82
                 - PhantomJS 1.9 (headless webkit browser)
83
                 - iOS < 6       (default mobile browser)
84
                 - Android < 4.4 (default mobile browser)
85
                 - Safari < 6    (desktop browser)
86
                 */
87
                if (type == 'css') {
88
                    if (!uaCssChecked) {
89
                        var ua = $window.navigator.userAgent.toLowerCase();
90
91
                        if (ua.indexOf('phantomjs/1.9') > -1) {
92
                            // PhantomJS ~1.9
93
                            useCssLoadPatch = true;
94
                        } else if (/iP(hone|od|ad)/.test($window.navigator.platform)) {
95
                            // iOS < 6
96
                            var v = $window.navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
97
                            var iOSVersion = parseFloat([parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)].join('.'));
98
                            useCssLoadPatch = iOSVersion < 6;
99
                        } else if (ua.indexOf('android') > -1) {
100
                            // Android < 4.4
101
                            var androidVersion = parseFloat(ua.slice(ua.indexOf('android') + 8));
102
                            useCssLoadPatch = androidVersion < 4.4;
103
                        } else if (ua.indexOf('safari') > -1) {
104
                            // Safari < 6
105
                            var versionMatch = ua.match(/version\/([\.\d]+)/i);
106
                            useCssLoadPatch = versionMatch && versionMatch[1] && parseFloat(versionMatch[1]) < 6;
107
                        }
108
                    }
109
110
                    if (useCssLoadPatch) {
111
                        var tries = 1000; // * 20 = 20000 miliseconds
112
                        var interval = $interval(function () {
113
                            try {
114
                                el.sheet.cssRules;
0 ignored issues
show
introduced by
The result of the property access to el.sheet.cssRules is not used.
Loading history...
115
                                $interval.cancel(interval);
116
                                el.onload();
117
                            } catch (e) {
118
                                if (--tries <= 0) {
119
                                    el.onerror();
120
                                }
121
                            }
122
                        }, 20);
123
                    }
124
                }
125
126
                return deferred.promise;
127
            };
128
129
            return $delegate;
130
        }]);
131
    }]);
132
})(angular);